package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.controller.form.GetCommentByTopicId;
import com.woniuxy.controller.form.TopicCommentForm;
import com.woniuxy.controller.info.Result;
import com.woniuxy.model.Comment;
import com.woniuxy.dao.CommentDao;
import com.woniuxy.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.util.ObjectRedisTemplate;
import com.woniuxy.util.WoniuCopyUtil;
import com.woniuxy.util.exception.NotfindCommentException;
import com.woniuxy.util.exception.code.CommentExceptionCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-19
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {

    @Resource
    private  ObjectRedisTemplate objectRedisTemplate;
    @Override
    public Result getCommentByTopicId(GetCommentByTopicId getCommentByTopicId) {
        List<Object> range = objectRedisTemplate.opsForList().range("Topic:id" + getCommentByTopicId.getTopicId() + "comment:", 0, -1);

        if(range.size()==0){
            /**
             * 查数据库
             */
            //数据库里面没有
            throw new NotfindCommentException(CommentExceptionCode.Comment_NOTFIND_ERROR);
        }
        List<Comment> comments = WoniuCopyUtil.copyMany(range, Comment.class);
        return Result.getInstanceList(Comment.class).setData(comments);

    }

    @Override
    @Transactional
    public Result addTopicComment(TopicCommentForm topicCommentForm) {
        System.out.println(topicCommentForm);
        Comment comment = WoniuCopyUtil.copyOne(topicCommentForm, Comment.class);
        System.out.println(comment);
        boolean save = save(comment);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_content",topicCommentForm.getCommentContent()).eq("account_id",topicCommentForm.getAccountId())
                .eq("topic_id",topicCommentForm.getTopicId());
        Comment one = getOne(queryWrapper);
        objectRedisTemplate.opsForList().leftPush("Topic:id"+topicCommentForm.getTopicId()+"comment:",one);
        return Result.getInstance().setMsg("添加评论成功");
    }
}
